package com.itheima.aspect;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j //日志文件
@Aspect // 切面类
@Component // 注册到Spring容器中
public class EmpLoginAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        //创建日志对象保存登录的信息
        EmpLoginLog empLoginLog = new EmpLoginLog();
        //获取用户提交的参数
        Object[] args = joinPoint.getArgs();
        // login(@ReqeustBody Emp emp), 所有只有一个参数
        Object arg = args[0];
        // 类型是Emp，所以强转成Emp
        Emp emp = (Emp) arg;
        // 可以设置登录的用户名与密码
        empLoginLog.setUsername(emp.getUsername());
        empLoginLog.setPassword(emp.getPassword());

        Object result = null;
        try {
            result = joinPoint.proceed();
            // 强转成Result类型? 切入点是登录方法LoginController.login方法，这个方法的返回值类型为Result
            //joinPoint.proceed(); 调用LoginController.login方法，返回Result类型对象
            Result loginResult = (Result) result;
            //登录是成功
            empLoginLog.setIsSuccess(loginResult.getCode().shortValue());
            // 登录成功时返回的data数据
            if(loginResult.getCode() == 1) {//只有登录成功才有token
                Object data = loginResult.getData();// return Result.success(loginInfo);
                // 强转成LoginInfo
                LoginInfo loginInfo = (LoginInfo) data;
                // 获取token
                String token = loginInfo.getToken();
                empLoginLog.setJwt(token);
            }else{
                empLoginLog.setJwt(loginResult.getMsg());
            }

        } catch (Throwable e) {
            empLoginLog.setIsSuccess((short)0);
            empLoginLog.setJwt("发生未知异常");
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            empLoginLog.setCostTime(end - start);//耗时
            empLoginLog.setLoginTime(LocalDateTime.now());//操作时间
            empLoginLogMapper.insert(empLoginLog);
        }

        return result;
    }
}
